package cn.iocoder.yudao.module.promotion.fod.job;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.api.member.vip.VipUserApi;
import cn.iocoder.yudao.module.promotion.fod.service.FirstOrderDiscountVipRechargeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 会员失效后自动恢复平台会员首单优惠资格 Job
 *
 * @author 山野羡民
 * @deprecated 已经不需要了，因为会监听会员过期事件，从而自动恢复会员平台首单优惠资格。
 */
@Slf4j
@Component
@Deprecated
public class FirstOrderDiscountAutoUnusedJob implements JobHandler {

    @Resource
    private FirstOrderDiscountVipRechargeService firstOrderDiscountVipRechargeService;

    @Resource
    private VipUserApi vipUserApi;

    @Override
    @TenantJob
    public String execute(String param) {
        Collection<Long> userIds = firstOrderDiscountVipRechargeService.getUsedUserIds();
        if (CollUtil.isEmpty(userIds)) {
            return "没有已使用过会员首单优惠资格的用户";
        }
        int count = 0;
        for (Long userId : userIds) {
            try {
                if (!vipUserApi.validVip(userId, null)) {
                    firstOrderDiscountVipRechargeService.updateUnused(userId);
                    count++;
                }
            } catch (Exception e) {
                log.error("[execute][userId({}) 失效后自动恢复会员首单优惠资格失败]", userId, e);
            }
        }
        return String.format("会员失效后自动恢复会员首单优惠资格 %s 个", count);
    }

}
